"""
Evaluation metrics
"""

import numpy as np
import sklearn.metrics as metrics
import os
import glob
import cv2
from PIL import Image



def numeric_score(pred, gt):
    FP = np.float(np.sum((pred == 1) & (gt == 0)))
    FN = np.float(np.sum((pred == 0) & (gt == 1)))
    TP = np.float(np.sum((pred == 1) & (gt == 1)))
    TN = np.float(np.sum((pred == 0) & (gt == 0)))
    return FP, FN, TP, TN

def threshold(image):
    # t = filters.threshold_otsu(image, nbins=256)
    image[image >= 100] = 255
    image[image < 100] = 0
    return image


# def numeric_score(pred, gt):
#     FP = np.float(np.sum((pred == 255) & (gt == 0)))
#     FN = np.float(np.sum((pred == 0) & (gt == 255)))
#     TP = np.float(np.sum((pred == 255) & (gt == 255)))
#     TN = np.float(np.sum((pred == 0) & (gt == 0)))
#     return FP, FN, TP, TN


def get_acc(image, label):
    # image = threshold(image)
    FP, FN, TP, TN = numeric_score(image, label)
    acc = (TP + TN) / (TP + FN + TN + FP + 1e-10)
    sen = (TP) / (TP + FN + 1e-10)
    fdr = (FP) / (FP + TP + 1e-10)
    return acc, sen, fdr


def numeric_score_fov(pred, gt, mask):
    FP = np.float(np.sum((pred == 1) & (gt == 0) & (mask == 1)))
    FN = np.float(np.sum((pred == 0) & (gt == 1) & (mask == 1)))
    TP = np.float(np.sum((pred == 1) & (gt == 1) & (mask == 1)))
    TN = np.float(np.sum((pred == 0) & (gt == 0) & (mask == 1)))
    return FP, FN, TP, TN



def AUC(path):
    all_auc = 0.
    file_num = 0
    auc=[]
    for file in glob.glob(os.path.join(path, 'gt', '*')):
        base_name = os.path.basename(file)

        #pred_path = os.path.join(path, 'baseline_300_0', base_name.replace("_centerline_overlay.tif", ".png"))
        # pred_path = os.path.join(path, 'our_0', base_name.replace(".tif", ".png"))
        pred_path = os.path.join(path, '111_0', base_name )

        label = cv2.imread(file, flags=-1)
        pred_image = cv2.imread(pred_path, flags=-1)

        pred_image = pred_image.flatten() / 255
        label = np.uint8(label.flatten() / 255)

        auc_score = metrics.roc_auc_score(label, pred_image)
        all_auc += auc_score
        file_num += 1
        auc.append(auc_score)
        ############
        ###################################   2022.0116 Doctor Ma   ####################################
        # f = open("metrics_unet_ccm120.csv", "w")
        # f.write("AUC\n")
        # for i in range(len(auc)):
        #     f.write(str(auc[i]) + "\n")##################
        # f.close()
    avg_auc = all_auc / file_num
    return avg_auc,np.array(auc)

def AccSenSpe(path):
    all_sen = []
    all_acc = []
    all_spe = []
    all_dice = []
    for file in glob.glob(os.path.join(path, 'gt', '*')):
        base_name = os.path.basename(file)
        # pred_path = os.path.join(path, '18_0', base_name.replace("_centerline_overlay.tif", ".png"))
        # pred_path = os.path.join(path, '700_0', base_name.replace(".tif", ".png"))
        pred_path = os.path.join(path, '111_0', base_name )

        pred = cv2.imread(pred_path, flags=0)

        label = cv2.imread(file, flags=0)

        pred = pred // 255
        label = label // 255

        FP, FN, TP, TN = numeric_score(pred, label)
        acc = (TP + TN) / (TP + FP + TN + FN)
        sen = TP / (TP + FN)
        spe = TN / (TN + FP)
        dice = (2*TP)/(FP+2*TP+FN)
        all_acc.append(acc)
        all_sen.append(sen)
        all_spe.append(spe)
        all_dice.append(dice)
    avg_acc, avg_sen, avg_spe,avg_dice = np.mean(all_acc), np.mean(all_sen), np.mean(all_spe),np.mean(all_dice)
    var_acc, var_sen, var_spe,var_dice = np.var(all_acc), np.var(all_sen), np.var(all_spe),np.var(all_dice)

    return avg_acc, var_acc, avg_sen, var_sen, avg_spe, var_spe,avg_dice,var_dice


def FDR(path):
    all_fdr = []
    for file in glob.glob(os.path.join(path, 'gt', '*')):
        base_name = os.path.basename(file)
        # pred_path = os.path.join(path, '18_0', base_name.replace("_centerline_overlay.tif", ".png"))
        # pred_path = os.path.join(path, '700_0', base_name.replace(".tif", ".png"))
        pred_path = os.path.join(path, '111_0', base_name )

        pred = cv2.imread(pred_path, flags=0)
        label = cv2.imread(file, flags=0)

        pred = pred // 255
        label = label // 255

        FP, FN, TP, TN = numeric_score(pred, label)
        fdr = FP / (FP + TP)
        all_fdr.append(fdr)
    return np.mean(all_fdr), np.var(all_fdr)


if __name__ == '__main__':
    # predicted root path
    path = '/home/jiayu/MyProject_2022/Total_Dataset/LCell_datasets/test/'
    # auc = AUC(path)
    acc, var_acc, sen, var_sen, spe, var_spe,dice,var_dice = AccSenSpe(path)
    fdr, var_fdr = FDR(path)
    # auc,auc_list = AUC(path)
    print("sen:{0:.4f} +- {1:.4f}".format(sen, var_sen))
    print("fdr:{0:.4f} +- {1:.4f}".format(fdr, var_fdr))
    print("dice:{0:.4f} +- {1:.4f}".format(dice, var_dice))
    # print("acc:{0:.4f}".format(acc))
    # print("sen:{0:.4f}".format(sen))
    # print("spe:{0:.4f}".format(spe))
    # print("auc:{0:.4f}".format(auc))
    # print("auc:{0:.4f}".format(dice))

